package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class TrackReceiver {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TrackInfoService trackInfoService;
    /**
     * 更细声音播放数
     * @param trackStatMqVo
     * @param message
     * @param channel
     * @return
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK,durable = "true",autoDelete = "false"),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE),
            key = {MqConst.ROUTING_TRACK_STAT_UPDATE}
    ))
    public void updateTrackStat(String trackStatMqVo, Message message, Channel channel){
        //  判断当前队列中是否有数据
        if (!StringUtils.isEmpty(trackStatMqVo)) {
            ////  将这个字符串转换为实体对象;
            TrackStatMqVo trackStatMqVo1 = JSONObject.parseObject(trackStatMqVo, TrackStatMqVo.class);
            String businessNo = trackStatMqVo1.getBusinessNo();
            //  防止消息重复消费.
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(businessNo, "1", 30, TimeUnit.SECONDS);

            if (flag) {
                try {
                    //  调用服务层方法.保存播放数
                    trackInfoService.updateTrackStat(trackStatMqVo1);
                } catch (Exception e) {
                    log.error(e.getMessage());
                    //保存失败，需要重试消费，删除key保证可以再次 调用服务层方法.保存播放数
                    this.redisTemplate.delete(businessNo);
                }
            }

            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
